#include "./mux.h"
#include "../device/gpio.h"

namespace driver {

using namespace device::gpio;

using PL = PC<8>;
using CP = PC<9>;
using Q7 = PA<15>;

Mux::Mux() {
    RCC->APB2ENR |= RCC_APB2ENR_IOPCEN;

    config_pp_out<PL, CP>();
    config_float_input<Q7>();
}

uint8_t Mux::read() {
    AUTO_LOCK(m_mutex);

    uint8_t val = 0;
    PL::clr();
    PL::set();

    for (uint8_t i = 0; i < 8; i ++) {
        val <<= 1;
        if (Q7::read()) {
            val ++;
        }
        CP::set();
        CP::clr();
    }
    return val;
}

uint8_t Mux::status() {
    using namespace utils;
    uint8_t tmp = read();
    return is_clr_bit<0>(tmp) +
        (is_clr_bit<2>(tmp) << 1) +
        (is_clr_bit<3>(tmp) << 2) +
        (is_clr_bit<4>(tmp) << 3);
}

}
